import React, { useEffect } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Row,
  Col,
  Space,
  Tag,
  Button,
} from 'antd';
import { TeamOutlined } from '@ant-design/icons';
import { Team } from '../../types/rbac';
import { useDepartmentTree } from '../../hooks/business/useDepartments';

const { TextArea } = Input;
const { Option } = Select;

// 团队表单数据类型
interface TeamFormData {
  name: string;
  code: string;
  description?: string;
  departmentId?: string;
  status: 'active' | 'inactive';
}

interface TeamFormProps {
  visible: boolean;
  team?: Team;
  onSubmit: (values: TeamFormData) => Promise<void>;
  onCancel: () => void;
  loading?: boolean;
}

const TeamForm: React.FC<TeamFormProps> = ({
  visible,
  team,
  onSubmit,
  onCancel,
  loading = false,
}) => {
  const [form] = Form.useForm();
  const { departmentTree, loading: departmentLoading } = useDepartmentTree();

  useEffect(() => {
    if (visible) {
      if (team) {
        // 处理后端返回的数字状态：1为启用，0为禁用
        const statusValue = team.status === 1 || team.status === 'active' ? 'active' : 'inactive';
        form.setFieldsValue({
          name: team.name,
          code: team.code,
          description: team.description,
          departmentId: team.departmentId,
          status: statusValue,
        });
      } else {
        form.resetFields();
      }
    }
  }, [visible, team, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      await onSubmit(values);
      form.resetFields();
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 递归构建部门选项
  const buildDepartmentOptions = (departments: any[], level = 0): React.ReactNode[] => {
    const options: React.ReactNode[] = [];
    
    departments.forEach(dept => {
      const prefix = '　'.repeat(level); // 使用全角空格缩进
      options.push(
        <Option key={dept.id} value={dept.id}>
          {prefix}{dept.name}
        </Option>
      );
      
      if (dept.children && dept.children.length > 0) {
        options.push(...buildDepartmentOptions(dept.children, level + 1));
      }
    });
    
    return options;
  };

  return (
    <Modal
      title={
        <Space>
          <TeamOutlined />
          <span>{team ? '编辑团队' : '新建团队'}</span>
        </Space>
      }
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={900}
      style={{ top: 20 }}
      destroyOnClose
    >
      <Form
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        onFinish={handleSubmit}
        initialValues={{
          status: 'active',
        }}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="团队名称"
              name="name"
              rules={[
                { required: true, message: '请输入团队名称' },
                { min: 2, max: 50, message: '团队名称长度为2-50个字符' },
              ]}
            >
              <Input placeholder="请输入团队名称，如：前端开发团队" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="团队代码"
              name="code"
              rules={[
                { required: true, message: '请输入团队代码' },
                { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '代码只能包含字母、数字和下划线，且不能以数字开头' },
              ]}
            >
              <Input placeholder="请输入团队代码，如：frontend_team" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="团队状态"
              name="status"
              initialValue="active"
            >
              <Select>
                <Option value="active">
                  <Space>
                    <Tag color="green">启用</Tag>
                    <span>正常工作状态</span>
                  </Space>
                </Option>
                <Option value="inactive">
                  <Space>
                    <Tag color="red">禁用</Tag>
                    <span>暂停工作状态</span>
                  </Space>
                </Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="所属部门"
              name="departmentId"
              rules={[{ required: true, message: '请选择所属部门' }]}
            >
              <Select
                placeholder="请选择所属部门"
                loading={departmentLoading}
                showSearch
                filterOption={(input, option) =>
                  option?.children?.toString().toLowerCase().includes(input.toLowerCase()) || false
                }
              >
                {departmentTree && buildDepartmentOptions(departmentTree)}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row>
          <Col span={24}>
            <Form.Item
              label="团队描述"
              name="description"
              labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
              rules={[
                { max: 200, message: '描述长度不能超过200个字符' },
              ]}
            >
              <TextArea
                placeholder="请输入团队描述，如：负责前端页面开发和用户体验优化"
                rows={3}
                showCount
                maxLength={200}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row>
          <Col span={24}>
            <Form.Item wrapperCol={{ offset: 3, span: 21 }}>
              <Space>
                <Button type="primary" htmlType="submit" loading={loading}>
                  {team ? '更新' : '创建'}
                </Button>
                <Button onClick={onCancel}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default TeamForm;